package com.ruoyi.iot.exchange.network.tcp.handler.impl;

import com.ruoyi.iot.domain.IotDevice;
import com.ruoyi.iot.domain.IotFrame;
import com.ruoyi.iot.domain.dto.ExchangeDTO;
import com.ruoyi.iot.exchange.network.tcp.cache.TcpChannelCache;
import com.ruoyi.iot.exchange.network.tcp.handler.dispatch.TCPDispatchHandler;
import com.ruoyi.iot.exchange.network.tcp.notify.DeviceStateNotify;
import com.ruoyi.iot.rabbitmq.ExchangeRabbitHelper;
import com.zxq.factory.decoder.FiledDecoderFactory;
import com.zxq.factory.enums.EField;
import lombok.extern.slf4j.Slf4j;



@Slf4j
public class HexRegistrationDispatchHandler extends TCPDispatchHandler {



    /**
     * 注册信息描述
     */
    public HexRegistrationDispatchHandler(IotFrame iotFrame) {
        super(iotFrame);
    }

    @Override
    protected byte[] patternHex(byte[] frame) {

        return frame;
    }


    @Override
    protected String takeDevId(byte[] frame) {

        return FiledDecoderFactory.instance().create(EField.Hex).decoder(frame) + "";
    }


    @Override
    public void decodeFrame() {
        byte[] frame = trimFrame();

        if(frame == null) {
            log.info("frame is empty!");
            return;
        }
        //起到注册帧的作用，写入后就不处理了
        String devCode = TcpChannelCache.getDevId(channel);
        if(devCode == null) {
            String devId = takeDevId(frame);
            if(devId == null) {
                log.info("not find device info,please check mysql config!");
                return;
            }
            DeviceStateNotify.getInstance().online(devId);
            TcpChannelCache.putNettyChannel(devId,channel);
            return;
        } else {
            TcpChannelCache.putNettyChannel(devCode, channel);
            log.info("dev:" + devCode + " update channel!");

        }

    }

    @Override
    protected Integer getDataLen(byte[] dataLenBuff) {
        return  (Integer) FiledDecoderFactory.instance().create(EField.Int).decoder(dataLenBuff);
    }






}
